//
//  Data.m
//  dingding
//
//  Created by dingding on 15/12/2.
//  Copyright © 2015年 dingding. All rights reserved.
//

#import "HttpHelper.h"
#import "Reachability.h"
#import "StringUtil.h"

@implementation HttpHelper

-(void)get:(NSString*)url prams:(NSDictionary*)dict func:(HttpCallback)funcs
{
    NSMutableString* sb=[NSMutableString stringWithString:url];
    NSRange range=[url rangeOfString:@"?"];
    if(range.location==NSNotFound){
        [sb appendString:@"?ios=1"];
    }else{
        [sb appendString:@"&ios=1"];
    }
    if(dict){
        [sb appendString:@"&"];
        NSArray *keys=[dict allKeys];
        for(unsigned int i=0;i<[keys count];i++){
            NSString* key=[keys objectAtIndex:i];
            NSString* value=[dict objectForKey:key];
            [sb appendString:key];
            [sb appendString:@"="];
            [sb appendString:[StringUtil encodeString:value]];
            [sb appendString:@"&"];
        }
        [sb deleteCharactersInRange:NSMakeRange(sb.length-1,1)];
    }
    NSString* result=[HttpHelper getSignUrl:sb];
    NSLog(@"%@",result);
    NSURL *url1= [NSURL URLWithString:result];
    // 创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
    [request setHTTPMethod:@"GET"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            funcs(response,data,error);
        });
    }];
    [task resume];
    //    NSLog(@"begin---");
    //     开启一个子线程发送一个异步请求，然后回到主线程在主线程当中执行下面大括号里面的代码刷新界面
    //     queue ：存放completionHandler这个任务  （任务是要存放到队列当中才能自动执行）
//    NSOperationQueue *queue = [NSOperationQueue mainQueue];  //mainQueue因为要刷新界面必须在主队列（也就是下面的大括号里面的代码就会在这个主队列当中执行
//    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:funcs];
}

-(void)getSync:(NSString*)url prams:(NSDictionary*)dict func:(HttpCallback)funcs
{
    NSMutableString* sb=[NSMutableString stringWithString:url];
    NSRange range=[url rangeOfString:@"?"];
    if(range.location==NSNotFound){
        [sb appendString:@"?ios=1"];
    }else{
        [sb appendString:@"&ios=1"];
    }
    if(dict){
        [sb appendString:@"&"];
        NSArray *keys=[dict allKeys];
        for(unsigned int i=0;i<[keys count];i++){
            NSString* key=[keys objectAtIndex:i];
            NSString* value=[dict objectForKey:key];
            [sb appendString:key];
            [sb appendString:@"="];
            [sb appendString:[StringUtil encodeString:value]];
            [sb appendString:@"&"];
            
        }
        [sb deleteCharactersInRange:NSMakeRange(sb.length-1,1)];
    }
    NSString* result=[HttpHelper getSignUrl:sb];
    
    NSURL *url1= [NSURL URLWithString:result];
    // 创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
    [request setHTTPMethod:@"GET"];
    
    NSData* data=[self sendSynchronousRequest:request returningResponse:nil error:nil];
    funcs(nil,data,nil);
}

- (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
{
    NSError __block *err = NULL;
    NSData __block *data;
    BOOL __block reqProcessed = false;
    NSURLResponse __block *resp;
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
       resp = _response;
       err = _error;
       data = _data;
       reqProcessed = true;
    }] resume];
    while (!reqProcessed) {
        [NSThread sleepForTimeInterval:0];
    }
    if(response){
       *response = resp;
    }
    if(error){
       *error = err;
    }
    return data;
}

-(void)post:(NSString*)url1 prams:(NSDictionary*)dict func:(HttpCallback)funcs
{
    NSMutableString* sb=[NSMutableString stringWithString:@""];
    NSArray *keys=[dict allKeys];
    for(unsigned int i=0;i<[keys count];i++){
        NSString* key=[keys objectAtIndex:i];
        NSString* value=[dict objectForKey:key];
        [sb appendString:key];
        [sb appendString:@"="];
        [sb appendString:[StringUtil encodeString:value]];
        [sb appendString:@"&"];
    }
    if(sb.length>0){
        [sb deleteCharactersInRange:NSMakeRange(sb.length-1,1)];
    }
    NSURL *url= [NSURL URLWithString:url1];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
    [request setHTTPMethod:@"POST"];
    //设置请求体
    [request setHTTPBody:[sb dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            funcs(response,data,error);
        });
    }];
    [task resume];
//    NSOperationQueue *queue = [NSOperationQueue mainQueue];  //mainQueue因为要刷新界面必须在主队列（也就是下面的大括号里面的代码就会在这个主队列当中执行
//    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:funcs];
}

-(void)postXml:(NSString*)url1 prams:(NSString*)xml func:(HttpCallback)funcs
{
    NSURL *url= [NSURL URLWithString:url1];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            funcs(response,data,error);
        });
    }];
    [task resume];
//    NSOperationQueue *queue = [NSOperationQueue mainQueue];  //mainQueue因为要刷新界面必须在主队列（也就是下面的大括号里面的代码就会在这个主队列当中执行
//    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:funcs];
}

-(bool)isNetworkConnect
{
    bool isNet=[[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable||[[Reachability reachabilityForInternetConnection] currentReachabilityStatus] !=NotReachable;
    return  isNet;
}


+(NSString*)getSignUrl:(NSString*)url
{
    NSLog(@"test:---%@",url);
    return url;
}

@end

